<template>
    <div>
        <div>
            <span style="position: absolute; margin-left: 65px">ext_json</span>
            <Card class="miniProgramTemplateUpdateExtJson" style="margin-left:120px; margin-bottom: 15px;">
                <JsonEditor
                        :options="{
                        confirmText: '确认',
                        cancelText: '取消',
                    }"
                        :objData="formValidate.ext_json"
                        v-model="formValidate.ext_json" >
                </JsonEditor>
            </Card>
        </div>
        <div>
            <Form :label-width="120" ref="formValidate" :model="formValidate" :rules="ruleValidate">
                <FormItem label="名称" prop="name">
                    <Input v-model="formValidate.name"></Input>
                </FormItem>
                <FormItem label="应用项目类型" prop="app_project_type_id">
                    <Select v-model="formValidate.app_project_type_id" placeholder="请选择应用项目类型">
                        <Option v-for="type in appProjectTypeList" :value="type.id">{{type.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="微信模板" prop="wx_template_id">
                    <Select v-model="formValidate.wx_template_id" @on-change="handleSelectWxTemplate" placeholder="请选择微信模板" filterable>
                        <Option v-for="template in wechatTemplateList"
                                :value="template.template_id"
                                :label="template.user_desc"
                        >
                            <div style="width: 120px">
                                描述:{{template.user_desc}}
                            </div>
                            <span>模板版本号:{{template.user_version}}</span>
                            <Tooltip placement="right" :transfer=true max-width="350" style="margin-left: 5px">
                                <Icon type="md-alert" size="10" />
                                <div slot="content">
                                    <p>模板ID：{{template.template_id}}</p>
                                    <p>模板版本号：{{template.user_version}}</p>
                                    <p>描述：{{template.user_desc}}</p>
                                    <p>创建时间：{{formatDate(template.create_time)}}</p>
                                </div>
                            </Tooltip>
                        </Option>
                    </Select>
                    <Card style="margin-top: 10px" v-model="cardInfo.data">
                        <p>模板ID：{{cardInfo.data.template_id}}</p>
                        <p>模板版本号：{{cardInfo.data.user_version}}</p>
                        <p>描述：{{cardInfo.data.user_desc}}</p>
                        <p>创建时间：{{formatDate(cardInfo.data.create_time)}}</p>
                    </Card>
                </FormItem>
                <FormItem  label="展示图片(上限6张)" prop="images">
                    <upload-img
                            v-model="formValidate.images"
                            :upload-url="uploadUrl"
                            :headers="uploadImgUrlHeader"
                            :is-many="true"
                            :max-size="2048"
                            :is-only-url="true"
                            :numLimit=imgNumLimit
                    ></upload-img>
                </FormItem>
                <FormItem label="备注" prop="remark">
                    <Input v-model="formValidate.remark" type="textarea"></Input>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
                    <Button @click="handleCancel()" style="margin-left: 8px">取消</Button>
                </FormItem>
            </Form>
        </div>
    </div>
</template>
<script>
    import {mapState, mapActions} from 'vuex';
    import apiService from '../../api/miniProgramTemplate';
    import appProjectTypeApiService from '../../api/appProjectType';
    import UploadImg from "../components/uploadImg";
    export default {
        props: {
            itemData: {
                type: Object,
                default: {}
            }
        },
        components: {
            UploadImg
        },
        computed: {
            ...mapState({
                loginToken: state => state.user.token
            }),
            uploadImgUrlHeader() {
                return {
                    Authorization: `${this.loginToken}`,
                };
            }
        },
        data () {
            return {
                //应用项目类型列表
                appProjectTypeList: [],
                //微信模板列表
                wechatTemplateList: [],
                //上传图片
                uploadUrl: apiService.uploadPicUrl,
                imgNumLimit: 6,
                //表单信息
                formValidate: {
                    name: '',
                    app_project_type_id: 0,
                    wx_template_id: -1,
                    ext_json: {},
                    remark: '',
                },
                ruleValidate: {
                    name: [
                        { required: true, message: '请填写名称', trigger: 'blur' }
                    ],
                    app_project_type_id: [
                        // { required: true, message: '请选择应用项目类型', trigger: 'change' }
                    ],
                    wx_template_id: [
                        // { required: true, message: '请选择微信模板', trigger: 'change' }
                    ],
                },
                cardInfo: {
                    visible: true,
                    data: {},
                },
            }
        },
        methods: {
            handleSelectWxTemplate(e) {
                this.handleChangeCardInfoData(e);
            },
            handleChangeCardInfoData(wxTemplateId) {
                let wxTemplistIndex = this.findFieldValInObj(this.wechatTemplateList, 'template_id', wxTemplateId);
                this.cardInfo.data = {
                    'template_id': this.wechatTemplateList[wxTemplistIndex].template_id,
                    'user_version': this.wechatTemplateList[wxTemplistIndex].user_version,
                    'user_desc': this.wechatTemplateList[wxTemplistIndex].user_desc,
                    'create_time': this.wechatTemplateList[wxTemplistIndex].create_time,
                };
            },
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        if (this.formValidate.app_project_type_id === 0) {
                            this.$Message.error('请选择应用项目类型');
                        } else if (this.formValidate.wx_template_id === -1) {
                            this.$Message.error('请选择微信模板');
                        } else if (this.formValidate.hasOwnProperty('images') && this.formValidate.images.length > this.imgNumLimit) {
                            this.$Message.error('最多上传' + this.imgNumLimit + '张图片');
                        } else {
                            this.operatorRequestHandler(
                                apiService.miniProgramTemplateUpdate(this.itemData.id, this.formValidate),
                                () => {
                                    this.$emit('on-close-customize-update');
                                }
                            )
                        }
                    } else {
                        this.$Message.error('请填写相应必填项');
                    }
                })
            },
            handleCancel () {
                this.$emit('on-close-customize-update');
            },
            formatDate(timestamp){
                let date = new Date(timestamp*1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
                let year = date.getFullYear(),
                    month = ("0" + (date.getMonth() + 1)).slice(-2),
                    sdate = ("0" + date.getDate()).slice(-2),
                    hour = ("0" + date.getHours()).slice(-2),
                    minute = ("0" + date.getMinutes()).slice(-2),
                    second = ("0" + date.getSeconds()).slice(-2);
                return year + "-"+ month +"-"+ sdate +" "+ hour +":"+ minute +":" + second;
            },
            /**
             * 通过数组的id值返回索引
             * 条件为true时，返回索引；否则返回-1
             */
            findFieldValInObj(arr, key, value) {
                return arr.findIndex(res => res[key] === value);
            },
        },
        created() {
            this.operatorRequestHandler(
                //获取应用项目类型列表
                appProjectTypeApiService.appProjectTypeList(),
                (res) => {
                    if (res.data.length > 0) {
                        this.appProjectTypeList = res.data;
                    }
                },
                null,
                '',
                false
            );

            this.operatorRequestHandler(
                //获取微信模板列表
                apiService.wxTemplateList(),
                (res) => {
                    if (res.data.length > 0) {
                        this.wechatTemplateList = res.data;
                        this.handleChangeCardInfoData(this.itemData.wx_template_id);
                    }
                },
                null,
                '',
                false
            );

            for (let field in this.formValidate) {
                this.formValidate[field] = this.itemData[field];
            }
            this.formValidate.ext_json = this.itemData.ext_json.length == 0 ? {} : this.itemData.ext_json;
            if (this.itemData.images.length > 0 ) {
                this.$nextTick(()=>{
                    this.formValidate.images = this.itemData.images;
                });
            }
        }
    }
</script>
<style>
    .pure-form select {
        height: 1.50rem;
    }
    .miniProgramTemplateUpdateExtJson .block_content .key-input,.miniProgramTemplateUpdateExtJson .block_content .val-input {
        width: 85px;
        border: 1px solid #dcdee2;
        border-radius: 4px;
    }

    .miniProgramTemplateUpdateExtJson:hover{
        width: 600px;
    }

    /*json编辑输入框长度样式修改*/
    .f-input {
        width: 410px;
    }

    /*json编辑下拉伸展按钮左移*/
    .collapse-down {
        position: absolute;
        left: -30px;
    }
</style>
